package com.fnst.common.facecomp.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fnst.common.facecomp.exception.ParamException;
import com.fnst.common.facecomp.model.CompareData;
import com.fnst.common.facecomp.model.T036FacecompCompare;
import com.fnst.common.facecomp.service.ComparePhotoService;
import com.fnst.common.facecomp.utils.Utils;

import sun.misc.BASE64Encoder;

/**
 * Servlet implementation class ImgContrast
 */
public class CompareServlet extends AbstractDetectServlet {
	private static final long serialVersionUID = 1L;
	
	protected Logger log = LoggerFactory.getLogger(getClass());
	private ComparePhotoService cps = new ComparePhotoService();
	
	private static final int COMPARE_TIMES_LIMIT = 3;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CompareServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		String pic1 = request.getParameter("pic1");
		String idNumber = request.getParameter("idNumber");
		String redirectUrl = request.getParameter("redirectUrl");
		String pic2A = request.getParameter("pic2A");
		String pic2B = request.getParameter("pic2B");
		String orderNumber = request.getParameter("orderNumber");
		String title = request.getParameter("title");
		
		log.info("pic1: " + pic1);
		log.info("idNumber: " + idNumber);
		log.info("redirectUrl: " + redirectUrl);
		log.info("pic2A: " + pic2A);
		log.info("pic2B: " + pic2B);
		log.info("orderNumber: " + orderNumber);
		log.info("title: " + title);		
		
		try{
			//检查识别次数
			List orderList = commonDao.selectT036FacecompCompareByOrderNumber(orderNumber);
			if(orderList != null && orderList.size() >= COMPARE_TIMES_LIMIT){
				request.setAttribute("error", "一个订单号最多识别"+COMPARE_TIMES_LIMIT+"次");
				request.setAttribute("pic1", pic1);
				request.setAttribute("idNumber", idNumber);
				request.setAttribute("pic2A", pic2A);
				request.setAttribute("pic2B", pic2B);
				request.setAttribute("orderNumber", orderNumber);
				request.setAttribute("title", title);
				request.setAttribute("redirectUrl", redirectUrl);				
				request.getRequestDispatcher(PAGE_COMPARE).forward(request, response);
				return;
			}
			
			//对比照片
			CompareData compareData = new CompareData();
			compareData.setCardId(idNumber);
			compareData.setComparePhoto(getBase64ByFilename(getUploadPath("") + pic1));
			if(pic2A != null && pic2A.trim().length() != 0){
				compareData.setIdPhoto1(getBase64ByFilename(getSavePath("") + pic2A));
			}
			if(pic2B != null && pic2B.trim().length() != 0){
				compareData.setIdPhoto2(getBase64ByFilename(getSavePath("") + pic2B));
			}
			
			cps.execute(compareData);
	
			//测试数据
//			compareData.setResult("90");
//			compareData.setErrorMsg("ok");
			
			//添加流程信息
			T036FacecompCompare t036 = new T036FacecompCompare();
			t036.setInsertTime(new Date());
			t036.setIdNumber(idNumber);
			t036.setOrderNumber(orderNumber);
			t036.setResult(compareData.getResult());
			t036.setErrorMsg(compareData.getErrorMsg());
			commonDao.addT036FacecompCompare(t036);
			
			Map resultMap = new HashMap();
			resultMap.put("result", compareData.getResult());
			resultMap.put("errorMsg", compareData.getErrorMsg());
			resultMap.put("orderNumber", t036.getOrderNumber());
			sendRedirect(response, redirectUrl, Utils.changeMapToJSONString(resultMap));			
		}catch(Exception e){
			log.error(e.getMessage(), e);
			Map resultMap = new HashMap();
			resultMap.put("result", ParamException.COMPARE_ERROR);
			resultMap.put("errorMsg", "识别错误");
//			String jsonResult = Utils.changeMapToJSONString(resultMap);
//			String responseStr = redirectUrl + "?result="+jsonResult;
//			log.error("responseStr: " + responseStr);
//			response.sendRedirect(responseStr);
			sendRedirect(response, redirectUrl, Utils.changeMapToJSONString(resultMap));
		}
	}
	
	public String getBase64ByFilename(String fileName) {
		File file = new File(fileName);
		FileInputStream inputFile = null;
		byte[] buffer = null;
		try {
			inputFile = new FileInputStream(file);
			buffer = new byte[(int) file.length()];
			inputFile.read(buffer);
			
		} catch (Exception e) {
			log.warn("getBase64ByFilename error: " + fileName, e);
		} finally {
			try{
				if(inputFile!=null){ 
					inputFile.close();
				}
			}catch(Exception e){};
		}
		return new BASE64Encoder().encode(buffer);
	}
	
}
